package com.dh.shiro.realm;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import com.dh.shiro.entity.Permission;
import com.dh.shiro.entity.Role;
import com.dh.shiro.entity.User;
import com.dh.shiro.sevice.RolePermissionService;
import com.dh.shiro.sevice.UserRoleService;
import com.dh.shiro.sevice.UserService;

/**
 * @author 作者 dinghao
 * @version 创建时间：2018年11月26日 下午2:00:48
 * @Description 类说明 :
 */
public class AuthRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;
	
	@Autowired
	private UserRoleService userRoleService;
	
	@Autowired
	private RolePermissionService rolePermissionService;

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		User user = (User) principals.fromRealm(this.getClass().getName()).iterator().next();
		List<Role> roleList = userRoleService.findByUid(user.getUid());
		List<Permission> permissionList = new ArrayList<>();
		if(!CollectionUtils.isEmpty(roleList)) {
			List<String> roles = roleList.stream().map(Role::getName).collect(Collectors.toList());
			info.addRoles(roles);
			List<String> permissions = new ArrayList<>();
			for (Role role : roleList) {
				permissionList = rolePermissionService.findByRid(role.getRid());
				if(!CollectionUtils.isEmpty(permissionList)) {
					permissions = permissionList.stream().map(Permission::getUrl).collect(Collectors.toList());
					info.addStringPermissions(permissions);
				}
			}
			return info;
		}
		return null;
	}

	/**
	 * 认证登录
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
		String username = usernamePasswordToken.getUsername();
		User user = userService.findByUsername(username);
		return new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
	}

}
